package com.ma.controller;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.ma.common.lang.Const;
import com.ma.common.lang.Result;
import com.ma.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.UUID;
@Slf4j
@RestController
public class AuthController extends BaseController {

    @Autowired
    private Producer producer;
    /*
            获取验证码接口
     */
    @GetMapping("/captcha")
    Result captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
/*
        //为了测试 先写死
        key="11111";
        code="aaaaa";*/

        //生成图片
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream bufferedOutputStream=new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",bufferedOutputStream);

        //生成64位编码
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(bufferedOutputStream.toByteArray());

        // 存储到redis中
        redisUtil.hset(Const.captcha_KEY,key,code,120);
        log.info("验证码 -- {} - {}", key, code);

        return Result.succ(MapUtil.builder()
                            .put("token",key)
                            .put("captchaImg",base64Img)
                            .build()
        );
    }
    /*
        获取当前登录用户信息
     */
    @GetMapping("/sys/userInfo")
    public Result getUserInfo(Principal principal){
        //获取登录用户名
        String name = principal.getName();
        SysUser sysUser = sysUserService.getAllByUsername(name);
        HashMap<String,Object> hashMap=new HashMap();
        hashMap.put("id",sysUser.getId());
        hashMap.put("username",sysUser.getUsername());
        hashMap.put("avatar",sysUser.getAvatar());
        return Result.succ(hashMap);
    }
}
